<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px" class="compact-form">
      <el-form-item label="客户姓名" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证号码" prop="idCardNumber">
        <el-input
          v-model="queryParams.idCardNumber"
          placeholder="请输入身份证号码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="诉讼/调解案号" prop="litigationMediationCaseNumber">
        <el-input
          v-model="queryParams.litigationMediationCaseNumber"
          placeholder="请输入诉讼/调解案号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="执行案号" prop="enforcementCaseNumber">
        <el-input
          v-model="queryParams.enforcementCaseNumber"
          placeholder="请输入执行案号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    
    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleSync"
          v-hasPermi="['system:statistic:list']"
        >同步数据</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:statistic:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    
    <el-table
      v-loading="loading"
      :data="list"
      border
      stripe
      size="mini"
      highlight-current-row
      style="width: 100%; margin-top: 20px;"
    >
      <el-table-column label="序号" type="index" width="50" align="center" />
      <el-table-column label="客户编号" prop="caseId" align="center" min-width="120" />
      <el-table-column label="客户姓名" prop="customerName" align="center" min-width="120" />
      <el-table-column label="身份证号码" prop="idCardNumber" align="center" min-width="180" />
      <el-table-column label="诉讼/调解案号" prop="litigationMediationCaseNumber" align="center" min-width="180" />
      <el-table-column label="执行案号" prop="enforcementCaseNumber" align="center" min-width="180" />
      <el-table-column label="同步时间" align="center" min-width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.syncTime) }}</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      :page-sizes="[20, 50, 100, 200, 500, -1]"
      :background="true"
    />
  </div>
</template>

<script>
import { listStatisticCases, exportStatisticCases, syncStatisticData } from '@/api/system/statistic'

export default {
  name: 'BankCustomerCasesStatistic',
  data() {
    return {
      loading: false,
      syncLoading: false,
      list: [],
      total: 0,
      showSearch: true,
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        customerName: undefined,
        idCardNumber: undefined,
        litigationMediationCaseNumber: undefined,
        enforcementCaseNumber: undefined
      }
    }
  },
  methods: {
    getList() {
      this.loading = true
      listStatisticCases(this.queryParams).then(res => {
        this.list = res.rows || []
        this.total = res.total || 0
        this.loading = false
      }).catch(err => {
        console.error("获取数据失败:", err)
        this.loading = false
      })
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 20,
        customerName: undefined,
        idCardNumber: undefined,
        litigationMediationCaseNumber: undefined,
        enforcementCaseNumber: undefined
      }
      this.getList()
    },
    // 导出客户案号统计
    handleExport() {
      this.$modal.confirm('是否确认导出所有客户案号统计数据项?').then(() => {
        this.exportLoading = true;
        
        // 构建查询参数字符串
        const queryParams = { ...this.queryParams };
        let queryString = Object.keys(queryParams)
          .filter(key => queryParams[key] !== undefined && queryParams[key] !== null && queryParams[key] !== '')
          .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(queryParams[key])}`)
          .join('&');
        
        if (queryString) {
          queryString = '?' + queryString;
        }
        
        // 从auth.js中导入getToken函数
        import('@/utils/auth').then(auth => {
          // 获取基础URL和token
          const baseUrl = process.env.VUE_APP_BASE_API;
          const token = auth.getToken();
          
          // 创建一个隐藏的a标签用于下载
          const link = document.createElement('a');
          link.style.display = 'none';
          link.href = `${baseUrl}/system/statistic/export${queryString}`;
          
          // 添加认证token到header
          const xhr = new XMLHttpRequest();
          xhr.open('GET', link.href, true);
          xhr.responseType = 'blob';
          xhr.setRequestHeader('Authorization', 'Bearer ' + token);
          
          // 显示加载中
          const loading = this.$loading({
            lock: true,
            text: '正在下载数据，请稍候',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          
          // 下载完成处理
          xhr.onload = () => {
            if (xhr.status === 200) {
              // 下载成功
              const blob = new Blob([xhr.response]);
              const url = window.URL.createObjectURL(blob);
              link.href = url;
              link.download = `客户案号统计_${new Date().getTime()}.xlsx`;
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link);
              window.URL.revokeObjectURL(url);
              this.$modal.msgSuccess('导出成功');
            } else {
              // 下载失败
              this.$modal.msgError('导出失败');
            }
            loading.close();
            this.exportLoading = false;
          };
          
          // 错误处理
          xhr.onerror = () => {
            this.$modal.msgError('导出失败，请稍后重试');
            loading.close();
            this.exportLoading = false;
          };
          
          // 发送请求
          xhr.send();
        });
      }).catch(() => {
        this.exportLoading = false;
      });
    },
    // 同步数据
    handleSync() {
      this.$confirm('是否确认从客户信息表同步有案号的客户数据?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.syncLoading = true;
        return syncStatisticData();
      }).then(res => {
        this.$modal.msgSuccess(res.msg);
        this.syncLoading = false;
        this.getList();
      }).catch(() => {
        this.syncLoading = false;
      });
    }
  },
  mounted() {
    this.getList()
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}
.mb8 {
  margin-bottom: 8px;
}
</style> 